package awt.robot;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Common stuff for all policies which deal with {@link ThreadPoolExecutor}s.
 * 
 * @author Mykhaylo Adamovych
 */
public abstract class AbstractExecutorPolicy implements IdlePolicy {
    /**
     * Solves deadlock when executor thread is blocked by EDT and it is also blocked and waiting for user input.
     */
    protected boolean isBlockedByEdt() {
        for (ThreadInfo info : ManagementFactory.getThreadMXBean().dumpAllThreads(true, true))
            if (info.getLockName() != null && info.getLockName().contains("java.awt.EventQueue$1AWTInvocationLock"))
                return true;
        return false;
    }

    @Override
    public boolean isIdle() {
        return !isThereActiveExecutors() || isBlockedByEdt();
    }

    protected abstract boolean isThereActiveExecutors();
}
